package com.sltx.controller;

import com.google.code.kaptcha.Producer;
import com.sltx.util.NetUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@RequestMapping("/test")
public class KaptchaController {

    @Autowired
    private Producer producer;

    @GetMapping("/getVerifyCode")
    public void getVerifyCode(HttpServletResponse response, HttpSession session) throws IOException {
        response.setContentType("image/jpeg");
        String text = producer.createText();
        session.setAttribute("vf", text);
        BufferedImage image = producer.createImage(text);
        try (ServletOutputStream sos = response.getOutputStream()) {
            ImageIO.write(image, "jpg", sos);
        }
    }
    @RequestMapping("/test3")
    public String test3() {
        return "1";
    }

    @RequestMapping("/getCal")
    public void getCal(HttpServletResponse response, HttpSession session) throws IOException {
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        System.out.println("当前生成的字符串为:" + text);
        //个位数字相加
        String s1 = text.substring(0, 2);
        String s2 = text.substring(2, 4);
        int count = Integer.valueOf(s1).intValue() + Integer.valueOf(s2).intValue();
        System.out.println("计算结果为:" + count);
        //生成图片验证码
        BufferedImage image = producer.createImage(s1 + "+" + s2 + "=?");
        try (ServletOutputStream sos = response.getOutputStream()) {
            ImageIO.write(image, "jpg", sos);
        }
    }

    @RequestMapping("/ip")
    public String getip(HttpServletRequest request) {
        String ipAddress = NetUtils.getIpAddress(request);
        return ipAddress;
    }

}

